/*******************************************************************************
 * Copyright 2011 See AUTHORS file.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

package game.breeze.ani;

import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.utils.Disposable;

public class Animation implements Disposable {
	public static final int ANIMATION_LOOPING = 0;
	public static final int ANIMATION_NONLOOPING = 1;

	private TextureRegion[] keyFrames;
	private float frameDuration;
	private int frame = 0;
	private boolean changed;
	private float duration;
	private float durCopy;
	private float preStateTime;
	private boolean done = false;

	public Animation(float frameDuration, int duration, TextureRegion... keyFrames) {
		this.frameDuration = frameDuration;
		this.keyFrames = keyFrames;
		this.duration = duration;
		this.durCopy = duration;
	}

	public TextureRegion getKeyFrame(float stateTime, int mode) {
		// 有完成时间,且动画完成
		if (done) {
			return null;
		}
		int frameNumber = (int) (stateTime / frameDuration);

		if (mode == ANIMATION_NONLOOPING) {
			frameNumber = Math.min(keyFrames.length - 1, frameNumber);
		} else {
			frameNumber = frameNumber % keyFrames.length;
		}
		changed = frame != frameNumber;
		frame = frameNumber;
		// 需要检查动画是否完成
		if (durCopy > 0) {
			if (preStateTime == 0) {
				preStateTime = stateTime;
			} else {// 播放帧
				duration -= (stateTime - preStateTime);
				preStateTime = stateTime;
			}
		}
		// 如果有播放时间,并时间到.或者播放帧忆是最后一帧
		done = (durCopy > 0 && duration <= 0) || (mode == ANIMATION_NONLOOPING && keyFrames.length - 1 == frameNumber);
		return keyFrames[frame];
	}

	public void reset() {
		frame = 0;
		changed = false;
		duration = durCopy;
		preStateTime = 0;
		done = false;
	}

	public TextureRegion getKeyFrame(int frame) {
		if (done || (frame >= keyFrames.length)) {
			return null;
		}
		changed = frame != this.frame;
		this.frame = frame;
		return keyFrames[this.frame];
	}

	/**
	 * @return the done
	 */
	public boolean isDone() {
		return done;
	}

	/**
	 * @return the changed
	 */
	public boolean isChanged() {
		return changed;
	}

	/**
	 * @return the frameDuration
	 */
	public float getFrameDuration() {
		return frameDuration;
	}

	@Override
	public void dispose() {
		keyFrames = null;
	}
}
